package legoLab06;
import lejos.nxt.*;
import java.io.*;

public class DataLogger 
{
    private File f;
    private FileOutputStream fos;
    
    public DataLogger (String fileName)
    {
        try
        {	        
            f = new File(fileName);
            if( ! f.exists() )
            {
                f.createNewFile();
            }
            else
            {
                f.delete();
                f.createNewFile();
            }
             
            fos = new FileOutputStream(f);
        }
        catch(IOException e)
        {
            LCD.drawString(e.getMessage(),0,0);
            try {
				Thread.sleep(5000);
			} catch (InterruptedException e1) {}
            System.exit(0);
        }
    }
	
    public void writeSample( String[] sample )
    {
    	String sampleString = "";
    	for(int j = 0; j < sample.length ; j++){
    		sampleString += sample[j];
    		if(j < sample.length - 1) sampleString += ",";
    		LCD.drawString(sampleString, 0, 5);
    	}

        try
        {
            for(int i=0; i<sampleString.length(); i++)
            {
                fos.write((byte) sampleString.charAt(i));
            }

            // New line
            fos.write((byte)('\r'));
            fos.write((byte)('\n'));

        }
        catch(IOException e)
        {
            LCD.drawString(e.getMessage(),0,0);
            try {
				Thread.sleep(5000);
			} catch (InterruptedException e1) {}
            System.exit(0);
        }
    }
    
    public void writeSample( Integer[] sample )
    {
    	String sampleString = "";
    	for(int j = 0; j < sample.length ; j++){
    		sampleString += sample[j].toString();
    		if(j < sample.length - 1) sampleString += ",";
    		LCD.drawString(sampleString, 0, 5);
    	}

        try
        {
            for(int i=0; i<sampleString.length(); i++)
            {
                fos.write((byte) sampleString.charAt(i));
            }

            // New line
            fos.write((byte)('\r'));
            fos.write((byte)('\n'));

        }
        catch(IOException e)
        {
            LCD.drawString(e.getMessage(),0,0);
            try {
				Thread.sleep(5000);
			} catch (InterruptedException e1) {}
            System.exit(0);
        }
    }
	
    public void close()
    {
        try
        {
            fos.close();
        }
        catch(IOException e)
        {
            LCD.drawString(e.getMessage(),0,0);
            System.exit(0);
        }		 
    }
}

